package com.ljc;


import java.util.HashMap;
import java.util.Map;

/**
 * @author ljchen
 * @date 2022-08-05 16:00
 * @desc
 * Given a string s, find the length of the longest substring without repeating characters.
 * Example 1:
 *
 * Input: s = "abcabcbb"
 * Output: 3
 * Explanation: The answer is "abc", with the length of 3.
 * Example 2:
 *
 * Input: s = "bbbbb"
 * Output: 1
 * Explanation: The answer is "b", with the length of 1.
 * Example 3:
 *
 * Input: s = "pwwkew"
 * Output: 3
 * Explanation: The answer is "wke", with the length of 3.
 * Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.
 * Constraints:
 *
 * 0 <= s.length <= 5 * 104
 * s consists of English letters, digits, symbols and spaces.
 */
public class M3LengthOfLongestSubstring {
    public static void main(String[] args) {
        String str = "pwwkew";
        int subStr = lengthOfLongestSubstring(str);

        System.out.println(subStr + " : " + subStr);

    }


    public static String longestSubStr(String str) {
        if (str != null && str.length() > 0) {
            StringBuilder subStr = new StringBuilder();
            subStr.append(str.charAt(0));
            for (int i = 0; i < str.length(); i++) {
                String str1 = String.valueOf(str.charAt(i));
                String str2 = String.valueOf(str.charAt(i + 1));
                if (!str1.equals(str2)) {
                    subStr.append(str2);
                }else {
                    subStr = new StringBuilder();
                    subStr.append(str2);
                }
            }
            return subStr.toString();
        }
        return "";
    }

    public static int lengthOfLongestSubstring(String s) {
        int n = s.length(), ans = 0;
        Map<Character, Integer> map = new HashMap<>();
        int i = 1;
        for (int end = 0, start = 0; end < n; end++) {
            System.out.println("============第【" + i + "】次迭代" );
            System.out.println("end: " + end);
            System.out.println("start: " + start);
            char alpha = s.charAt(end);
            System.out.println("alpha(s.charAt(end)): " + alpha);
            if (map.containsKey(alpha)) {
                System.out.println("contains: " + true);
                start = Math.max(map.get(alpha), start);
                System.out.println("start: " + start);
            }
            ans = Math.max(ans, end - start + 1);
            System.out.println("ans: " + ans);
            map.put(s.charAt(end), end + 1);
            System.out.println("map.key: 【" + s.charAt(end) + "】value:【" + (end+1) + "】");

            i++;
        }
        return ans;
    }


}
